package pl.edu.agh.jemo.evolution.metrics;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedList;
import java.util.List;

public final class MetricMeanExtractor {

	public static void main(String[] args) throws IOException {

		List<BigDecimal> sums = new LinkedList<BigDecimal>();
		Integer fileCount = 0;
		File f = new File("C:\\metryki_temp");

		if (f.exists() && f.isDirectory()) {
			for (File txt : f.listFiles()) {
				if (!txt.getName().contains("meanValues")) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(new FileInputStream(txt)));
					String line = br.readLine();
					String[] lineArray = line.split(" ");
					while (line != null && lineArray.length == 2) {
						final Integer stepNo = Integer.valueOf(lineArray[0]);
						final BigDecimal value = BigDecimal.valueOf(Double
								.valueOf(lineArray[1]));
						if (stepNo >= sums.size()) {
			
							sums.add(value);
						} else {
							sums.add(stepNo, sums.remove(stepNo.intValue()).add(value));
						}
						line = br.readLine();
						lineArray = line != null ? line.split(" ") : null;
					}
					fileCount++;
				}
			}
			File output = new File("C:\\metryki_temp\\meanValues.txt");
			BufferedWriter bw = new BufferedWriter(new PrintWriter(output));
			int counter = 0;
			for (final BigDecimal value : sums) {
				final BigDecimal mean = value.divide(
						BigDecimal.valueOf(fileCount), RoundingMode.HALF_DOWN);
				bw.write(counter + " " + mean + "\r\n");
				counter++;
			}
			bw.close();

		}

	}
}
